'use strict';
module.exports = {
	/**
	 * 
	 */
	main: async (event) => {
		const db = uniCloud.database();
		const $ = db.command.aggregate;
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			_
		} = util;
		let {
			uid,
			todayStart
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		if (userInfo.role.includes('admin')) {
			//查询今日新增用户数
			res.num = await vk.baseDao.count({
				dbName: "uni-id-users",
				whereJson: {
					old_id: db.command.exists(false),
					register_date: _.gte(todayStart)
				}
			});

			//查询今日新用户充值总金额
			res.new_users_moneysum = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					pay_status: 1,
					user_register_date: _.gte(todayStart)
				}
			});


			//====查询充值订单里，今天一共有多少个新付费用户====
			// 执行聚合查询,今日充值新用户人数（注册时间是今天）。
			let newUsers_payNumber = await db.collection('a_recharge')
				.aggregate()
				.match({
					user_register_date: _.gte(todayStart),
					user_id: db.command.exists(true),
					pay_status: 1
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.newUsers_payNumber = newUsers_payNumber.data.length ? newUsers_payNumber.data[0].user_count
				.length : 0
			//====计算新付费用户结束====


			//====查询充值订单里，今天一共有多少个付费用户====
			// 执行聚合查询,今日充值人数
			let newRows_userid = await db.collection('a_recharge')
				.aggregate()
				.match({
					_add_time: db.command.gte(todayStart),
					user_id: db.command.exists(true),
					pay_status: 1
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.Users_payNumber = newRows_userid.data.length ? newRows_userid.data[0].user_count.length : 0
			//====计算今日付费用户结束====


			//查询今日充值笔数 
			res.today_recharges_Number = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					pay_status: 1,
					_add_time: _.gte(todayStart)
				}
			});

			//查询今日充值总金额
			res.today_Recharge_amount = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					pay_status: 1,
					_add_time: _.gte(todayStart)
				}
			});

			//复充人数
			let orderCollection = db.collection('a_recharge');
			let numberRePurchasers = await orderCollection.aggregate()
				.match({
					pay_status: 1,
					_add_time: _.gte(todayStart)
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.count('distinctBuyerCount')
				.end()
			console.log("numberRePurchasers=", numberRePurchasers);
			res.today_repeat_user = 0;
			if (numberRePurchasers.data.length > 0) {
				res.today_repeat_user = numberRePurchasers.data[0].distinctBuyerCount;
			}

			//复充金额(用户多次充值订单的总金额)
			let today_repeat_amount = await db.collection('a_recharge').aggregate()
				.match({
					pay_status: 1,
					_add_time: _.gte(todayStart)
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					},
					total_amount: {
						$sum: '$shifu_amount'
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.group({
					_id: null,
					grand_total: {
						$sum: '$total_amount'
					}
				})
				.project({
					_id: 0,
					grand_total: 1
				})
				.end();
			console.log("today_repeat_amount:" + today_repeat_amount);
			if (today_repeat_amount.data.length != 0) {
				res.today_repeat_amount = today_repeat_amount.data[0].grand_total
			}

			//复充率
			res.today_repeat_rate = 0 //在前端计算
			return res;
		}

		if (userInfo.role.includes('agent')) {
			//查询今日新增用户数
			res.num = await vk.baseDao.count({
				dbName: "uni-id-users",
				whereJson: {
					invite_code: userInfo._id,
					register_date: _.gte(todayStart)
				}
			});
			//查询今日新用户充值总金额
			res.new_users_moneysum = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					invite_code: userInfo._id,
					pay_status: 1,
					user_register_date: _.gte(todayStart)
				}
			});
			//====查询充值订单里，一共有多少个新付费用户====

			let new_jrczrs = await db.collection('a_recharge')
				.aggregate()
				.match({
					invite_code: userInfo._id,
					pay_status: 1, //状态为支付完成
					user_register_date: _.gte(todayStart),
					_add_time: _.gte(todayStart)
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			res.newUsers_payNumber = new_jrczrs.data.length ? new_jrczrs.data[0].user_count.length : 0
			//====计算新付费用户结束====


			//====查询充值订单里，一共有多少个付费用户====
			//查询一共有多少个符合条件的充值订单，条件为：已支付+记录时间为今天

			let jrczrs = await db.collection('a_recharge')
				.aggregate()
				.match({
					_add_time: _.gte(todayStart),
					pay_status: 1,
					invite_code: userInfo._id,
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			res.Users_payNumber = jrczrs.data.length ? jrczrs.data[0].user_count.length : 0
			//====计算今日付费用户结束====


			//查询今日充值笔数 
			res.today_recharges_Number = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					invite_code: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart)
				}
			});

			//查询今日充值总金额
			res.today_Recharge_amount = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					invite_code: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart)
				}
			});

			//复充人数
			let orderCollection = db.collection('a_recharge');
			let numberRePurchasers = await orderCollection.aggregate()
				.match({
					invite_code: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart)
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.count('distinctBuyerCount')
				.end()
			console.log("numberRePurchasers=", numberRePurchasers);
			res.today_repeat_user = 0;
			if (numberRePurchasers.data.length > 0) {
				res.today_repeat_user = numberRePurchasers.data[0].distinctBuyerCount;
			}

			//复充金额(用户多次充值订单的总金额)
			let today_repeat_amount = await db.collection('a_recharge').aggregate()
				.match({
					invite_code: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart)
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					},
					total_amount: {
						$sum: '$shifu_amount'
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.group({
					_id: null,
					grand_total: {
						$sum: '$total_amount'
					}
				})
				.project({
					_id: 0,
					grand_total: 1
				})
				.end();
			console.log("today_repeat_amount:" + today_repeat_amount);
			if (today_repeat_amount.data.length != 0) {
				res.today_repeat_amount = today_repeat_amount.data[0].grand_total
			}

			//复充率
			res.today_repeat_rate = 0 //在前端计算

			return res;
		}


		if (userInfo.role.includes('middleman')) {
			//查询今日新增用户数
			res.num = await vk.baseDao.count({
				dbName: "uni-id-users",
				whereJson: {
					middleman_id: userInfo._id,
					register_date: _.gte(todayStart)
				}
			});
			//查询今日新用户充值总金额
			res.new_users_moneysum = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					middleman_id: userInfo._id,
					pay_status: 1,
					user_register_date: _.gte(todayStart)
				}
			});



			//====查询充值订单里，今天一共有多少个新付费用户====
			let conditions1 = {
				middleman_id: userInfo._id,
				user_register_date: _.gte(todayStart),
				user_id: db.command.exists(true),
				pay_status: 1
			}
			// 执行聚合查询,今日充值新用户人数（注册时间是今天）。
			let newUsers_payNumber = await db.collection('a_recharge')
				.aggregate()
				.match(conditions1)
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.newUsers_payNumber = newUsers_payNumber.data.length ? newUsers_payNumber.data[0].user_count
				.length : 0
			//====计算新付费用户结束====


			//====查询充值订单里，今天一共有多少个付费用户====
			// 查询条件
			let conditions2 = {
				middleman_id: userInfo._id,
				_add_time: db.command.gte(todayStart),
				user_id: db.command.exists(true),
				pay_status: 1
			}
			// 执行聚合查询,今日充值人数
			let newRows_userid = await db.collection('a_recharge')
				.aggregate()
				.match(conditions2)
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.Users_payNumber = newRows_userid.data.length ? newRows_userid.data[0].user_count.length : 0
			//====计算今日付费用户结束====


			//查询今日充值笔数 
			res.today_recharges_Number = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					middleman_id: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart)
				}
			});

			//查询今日充值总金额
			res.today_Recharge_amount = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					middleman_id: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart)
				}
			});

			//复充人数
			let orderCollection = db.collection('a_recharge');
			let numberRePurchasers = await orderCollection.aggregate()
				.match({
					middleman_id: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart)
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.count('distinctBuyerCount')
				.end()
			console.log("numberRePurchasers=", numberRePurchasers);
			res.today_repeat_user = 0;
			if (numberRePurchasers.data.length > 0) {
				res.today_repeat_user = numberRePurchasers.data[0].distinctBuyerCount;
			}

			//复充金额(用户多次充值订单的总金额)
			let today_repeat_amount = await db.collection('a_recharge').aggregate()
				.match({
					middleman_id: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart)
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					},
					total_amount: {
						$sum: '$shifu_amount'
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.group({
					_id: null,
					grand_total: {
						$sum: '$total_amount'
					}
				})
				.project({
					_id: 0,
					grand_total: 1
				})
				.end();
			if (today_repeat_amount.data.length != 0) {
				res.today_repeat_amount = today_repeat_amount.data[0].grand_total
			}

			//复充率
			res.today_repeat_rate = 0 //在前端计算

			return res;
		}
		// 业务逻辑结束-----------------------------------------------------------
		return;
	}
}